import mitt from 'mitt'

const $mitt = mitt()

/**
 * 注册监听事件
 * @param eventName 监听事件的名称
 * @param callback  监听事件的回调
 */
export function registerEvent (eventName, callback) {
  $mitt.on(eventName, callback)

  const destroy = () => {
    $mitt.off(eventName, callback)
  }

  return {
    destroy
  }
}

export default function useEventBus(isCustom) {
	if (!isCustom) {
		return $mitt
	}

	let eventActions = []

	return {
		register: (eventName, callback) => {
			const listener = registerEvent(eventName, callback)

			eventActions.push(listener.destroy)

			return listener.destroy
		},
		destroy: (listener) => {
			if (listener) {
				eventActions = eventActions.filter(action => action !== listener)
				listener?.()
				return
			}

			// 如果没有传入 listener，则销毁所有注册的事件
			eventActions.forEach(action => action())
			eventActions = []
		},
		emit: (eventName, ...args) => {
			$mitt.emit(eventName, ...args)
		},
		on: (eventName, callback) => {
			$mitt.on(eventName, callback)
		},
		off: (eventName, callback) => {
			$mitt.off(eventName, callback)
		}
	}
}